package com.ys.controller.web.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ys.config.MenuId;
import com.ys.entity.sys.YsGrid;
import com.ys.entity.sys.YsMenu;
import com.ys.mapper.sys.SysMapper;
import com.ys.service.sys.CommonApiService;
import com.ys.util.StringUtil;
import com.ys.vo.W;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 
 * @author Jason
 *
 */
@Controller
@RequestMapping("/web/sys/ysGrid")
public class WebYsGridController {
	@Autowired
	private SysMapper sysMapper;
	
	@Autowired
	private CommonApiService<YsGrid> commonApiService;
	
	/**
	 * 新增
	 * @throws Exception 
	 */
	@GetMapping("/toAdd")
	public String toAdd(Model model) throws Exception{
		return commonApiService.toAdd(model, new YsGrid(), MenuId.YS_Grid, null, null);
	}
	
	/*
	 * 批量新增字段
	 */
	@GetMapping("/toBatchAddCol")
	public String toBatchAddCol(Model model, Long menuId, String tableName){
		
		if (menuId == null) {
			return W.error(model, "子列表所属菜单ID不能为空");
		}
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		Long gridId = ysMenu.getGridId();
		if (gridId == null) {
			return W.error(model, "尚未配置子列表");
		}
		
		if (tableName == null) {
			return W.error(model, "表名不能为空");
		}
		
		/*
		 *  字段详情数组
		 *  1、已有的字段
		 *  2、未有的字段
		 */
		List<ToBatchAddColDto.RowDto> rows = new ArrayList<ToBatchAddColDto.RowDto>();
		
		List<Map<String, Object>> listDetail = sysMapper.listSysCol(tableName);
		for(Map<String, Object> detail : listDetail) {
			String code = StringUtil.firstCharacterToLower(detail.get("code").toString());
			if ("id".equals(code)) {
				continue;
			}
			String name = detail.containsKey("name") ? detail.get("name").toString() : "待完善名称";
			rows.add(new ToBatchAddColDto.RowDto(gridId, code, name));
		}
		model.addAttribute("gridId", gridId);
		
		ToBatchAddColDto dto = new ToBatchAddColDto(rows);
		model.addAttribute("sonlist", dto);
		
		return "sys/ysGrid/toBatchAddCol";
	}
	@Data
	@AllArgsConstructor
	public static class ToBatchAddColDto{
		private List<RowDto> rows; // 

		@Data
		@AllArgsConstructor
		public static class RowDto{
			private Long gridId;
			private String code;
			private String name;
		}
	}
	
	/**
	 * 设置
	 * @throws Exception 
	 */
	@GetMapping("/toEdit")
	public String toSetting(Model model, Long id) throws Exception{
		return commonApiService.toEdit(model, id, new YsGrid(), MenuId.YS_Grid, null, null);
	}
}
